package controllers

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"supershare/backend/middleware"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// UploadController 文件上传控制器
type UploadController struct {
	web.Controller
}

// Upload 上传文件
func (c *UploadController) Upload() {

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取上传的文件
	f, h, err := c.GetFile("file")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取上传文件失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}
	defer f.Close()

	// 检查文件类型
	fileExt := strings.ToLower(filepath.Ext(h.Filename))
	allowExts := []string{".jpg", ".jpeg", ".png", ".gif"}
	allowed := false
	for _, ext := range allowExts {
		if ext == fileExt {
			allowed = true
			break
		}
	}

	if !allowed {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "只允许上传图片文件(.jpg, .jpeg, .png, .gif)",
		}
		c.ServeJSON()
		return
	}

	// 创建上传目录
	uploadDir := "static/uploads/" + fmt.Sprintf("%d", admin.FranchiseId) + "/" + time.Now().Format("2006/01/02")
	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建上传目录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 生成文件名
	timestamp := time.Now().UnixNano() / 1e6 // 毫秒时间戳
	fileName := fmt.Sprintf("%d%s", timestamp, fileExt)
	filePath := filepath.Join(uploadDir, fileName)

	// 保存文件
	if err := c.SaveToFile("file", filePath); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "保存文件失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回文件URL
	fileURL := "/" + filePath
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "上传成功",
		"data":    fileURL,
	}
	c.ServeJSON()
}

// UploadMulti 批量上传文件
func (c *UploadController) UploadMulti() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取上传的文件数量
	files, err := c.GetFiles("files")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取上传文件失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 创建上传目录
	uploadDir := "static/uploads/" + fmt.Sprintf("%d", admin.FranchiseId) + "/" + time.Now().Format("2006/01/02")
	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建上传目录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 保存文件并收集URL
	fileURLs := make([]string, 0)
	for i, _ := range files {
		fh := files[i]
		// 检查文件类型
		fileExt := strings.ToLower(filepath.Ext(fh.Filename))
		allowExts := []string{".jpg", ".jpeg", ".png", ".gif"}
		allowed := false
		for _, ext := range allowExts {
			if ext == fileExt {
				allowed = true
				break
			}
		}

		if !allowed {
			continue // 跳过不允许的文件类型
		}

		// 生成文件名
		timestamp := time.Now().UnixNano() / 1e6 // 毫秒时间戳
		fileName := fmt.Sprintf("%d%s", timestamp, fileExt)
		filePath := filepath.Join(uploadDir, fileName)

		// 保存文件
		f, err := fh.Open()
		if err != nil {
			continue
		}
		defer f.Close()

		// 创建目标文件
		dst, err := os.Create(filePath)
		if err != nil {
			continue
		}
		defer dst.Close()

		// 复制文件内容
		buf := make([]byte, 1024)
		for {
			n, err := f.Read(buf)
			if err != nil || n == 0 {
				break
			}
			dst.Write(buf[:n])
		}

		// 添加到URL列表
		fileURL := "/" + filePath
		fileURLs = append(fileURLs, fileURL)

	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "上传成功",
		"data":    fileURLs,
	}
	c.ServeJSON()
}
